<?php
/**
 * Created by PhpStorm.
 * User: lx
 * Date: 2020/1/3
 * Time: 14:38
 */
namespace app\mtadminapi\controller;

use app\command\controller\Common;
use app\command\controller\Generate;
use app\mtadminapi\model\MtShopHouseInstall;
use app\mtadminapi\model\MtShopHouseTypeitem;
use app\util\ReturnCode;
use app\util\Strs;
use think\Controller;
use app\mtadminapi\model\MtAdminSysAuth;
use think\cache\driver\Redis;
use think\facade\Session;
use think\Request;
use app\mtadminapi\model\MtBhArea;
use think\facade\Hook;
use app\mtadminapi\model\MtShopHouseBedtype;
use app\mtadminapi\model\MtAdminSysAccountRole;

class Base extends Controller
{
    const ADMINUSER = "adminuser"; // redis存储token时的标签
    public $adminUser = [];
    public $adminID;
    public $request;
    public $token;
    private $debug = [];

    public function __construct(){
        $this->request = \request();
    }

    /**
     * 权限列表
     * @param array $authGroupData
     * @return array
     */
    public function authList($authGroupData = []){
        if(!$authGroupData){
            $authGroupData = (new MtAdminSysAuth())->where("status","1")->select();
        }
        //调用递归
        $authList = (new Common)->recursion($authGroupData);
        return $this->bindSuccess("成功",$authList);
    }

    /**
     * token的获取存储
     * @param string $param
     * @return string|void
     */
    public function getToken($param = ""){
        if(empty($param)){
            $param = $this->request->param();
        }
        if(!cache("adminUser.adminID")){
            $adminID = Strs::randString(); // 随机串
            $this->adminUser['adminInfo']['adminID'] = $adminID;
        }else{
            $adminID = cache("adminUser.adminID");
        }
        $token = (new Generate())->createToken($adminID,$param);
        $redisCache = (new Redis)->set($token, $adminID, 3600);
        if($redisCache){
            return ["code" => 1,"adminID" => $adminID,"token" => $token];
        }else{
            return $this->error(ReturnCode::CACHE_SAVE_ERROR, "Token存储失败", $this->adminUser);
        }
    }
    /**
     * 中间件传参
     * @param $id
     * @param $data
     */
    public function middleDelivery($id,$data){
        // 中间件传参
        $this->request->param = [$id,$data];
    }

    /**
     * Error
     * @param $code
     * @param string $msg
     * @param array $data
     * @return array
     */
    public function bindError($code, $msg = '操作失败', $data = []){
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        Hook::listen("AdminApiRequest",['code' => $code,'msg' => $msg]);
        return $return;
    }

    /**
     * Success
     * @param string $msg
     * @param array $data
     * @param int $code
     * @return array
     */
    public function bindSuccess($msg = '操作失败', $data = [], $code = ReturnCode::SUCCESS){
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        Hook::listen("AdminApiRequest",['code' => $code,'msg' => $msg]);
        return $return;
    }

    public function buildFailed($code, $msg = '操作失败', $data = []) {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if (config('app.app_debug') && $this->debug) {
            $return['debug'] = $this->debug;
        }

        return $return;
    }

    protected function debug($data) {
        if ($data) {
            $this->debug[] = $data;
        }
    }

    /**
     * 房间地区数据处理
     * @param $area
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function areaHandle($area){
        if(empty($area)){
            return $area;
        }
        $Area = explode(":",$area);
        $Arr = (new MtBhArea())->where("areaId","in",$Area)->field("areaName")->select()->toArray();
        foreach ($Arr as $k => $v){
            $AreaArr[] = $v['areaName'];
        }
        return $AreaArr;
    }

    /**房间床数据处理
     * @param $bedSize
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bedSizeHandle($bedSize){
        if(empty($bedSize)){
            return $bedSize;
        }
        $bedSizeArr = explode(",",$bedSize);
        $bed = [];
        foreach ($bedSizeArr as $k => $v){
            $bedSize = explode(":",$v);
            $bedType = (new MtShopHouseBedtype())->where("id","in",[$bedSize[0],$bedSize[1]])->field("bedName")->select()->toArray();
            $bed[] = [$bedType[0]['bedName'],$bedType[1]['bedName']."m",$bedSize[2]."张"];
        }
        return $bed;
    }

    /**
     *  房间类型处理
     * @param $houseTypeItem
     */
    public function houseTypeHandle($houseTypeItem){
        if(empty($houseTypeItem)){
            return $houseTypeItem;
        }
        $houseTypeArr = explode(":",$houseTypeItem);
        $houseType = (new MtShopHouseTypeitem())->where([["typeID","in",$houseTypeArr],["status","=","1"]])->field("typeName")->select();
        return $houseType;
    }

    /**
     * 房间设施处理
     * @param $houseInstall
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function installHandle($houseInstall){
       if(empty($houseInstall)){
           return $houseInstall;
       }
        $houseInstallArr = explode(",",$houseInstall);
        $Arr = (new MtShopHouseInstall())->where([["id","in",$houseInstallArr],["status","=","1"]])->field("installName,parentID")->select()->toArray();
        foreach ($Arr as $k => $v){
            $parentIdArr[] = $v['parentID'];
        }
        $parentName = (new MtShopHouseInstall())->where("id",'in',$parentIdArr)->field("installName,id")->select()->toArray();
        $res = [];
        foreach ($Arr as $k => $v){
            foreach ($parentName as $key => $val){
                if($v['parentID'] == $val['id']){
                    $res[$val['installName']][] = $v['installName'];
                }
            }
        }
        return $res;
    }
    /**
     * 管理员权限
     * @param $adminID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminAuth($adminID){
        if(!$adminID){
            $adminID = $this->request->param("adminID");
            if(!$adminID){
                return $this->bindError(ReturnCode::EMPTY_PARAMS,"缺少参数adminID");
            }
        }
        $adminRole = (new MtAdminSysAccountRole())
            ->where(["adminID"=>$adminID])
            ->alias('accountRole') // 起别名
            ->join('mt_admin_sys_role role',"accountRole.roleID = role.roleID") // 联查角色表
            ->join("mt_admin_sys_role_auth roleAuth","role.roleID = roleAuth.roleID") //联查角色权限关联表
            ->find();
        if($adminRole){
            $adminRole = $adminRole->toArray();
        }
        $roleAuth = (new MtAdminSysAuth())->where("id","in",$adminRole['roleAuth'])->select(); //查询权限表
        if(!$roleAuth){
            return false;
        }
        $roleAuth = $roleAuth->toArray();
        $adminAuth = (new Common())->recursion($roleAuth); // 递归管理员权限
        return $adminAuth;
    }
}